package org.example.mynote.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.mynote.Entity.Note;
import org.example.mynote.dto.NoteCreateRequest;
import org.example.mynote.dto.NoteUpdateRequest;
import org.example.mynote.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/notes")
@Tag(name = "笔记相关接口")
@Slf4j
@SecurityRequirement(name = "BearerAuth")
public class NoteController {
    @Autowired
    private NoteService noteService;

    /**
     * (6) 新建笔记
     * URL: POST /api/notes
     */
    @PostMapping
    @Operation(summary = "在指定笔记本中新建一篇笔记")
    public ResponseEntity<Note> createNote(@RequestBody NoteCreateRequest request) {
        // NoteCreateRequest DTO: Long notebookId, String title, String content
        Note createdNote = noteService.createNote(request.getNotebookId(), request.getTitle(), request.getContent());
        return ResponseEntity.ok(createdNote);
    }

    /**
     * (7) 修改笔记
     * URL: PUT /api/notes/{id}
     */
    @PutMapping("/{id}")
    @Operation(summary = "根据ID修改笔记")
    public ResponseEntity<Note> updateNote(@PathVariable Long id, @RequestBody NoteUpdateRequest request) {
        // NoteUpdateRequest DTO: String title, String content
        Note updatedNote = noteService.updateNote(id, request.getTitle(), request.getContent());
        return ResponseEntity.ok(updatedNote);
    }

    /**
     * (8) 删除笔记
     * URL: DELETE /api/notes/{id}
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "根据ID删除笔记")
    public ResponseEntity<Void> deleteNote(@PathVariable Long id) {
        noteService.deleteNote(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * (9) 笔记搜索
     * URL: GET /api/notes/search?keyword=...
     */
    @GetMapping("/search")
    @Operation(summary = "根据关键词搜索当前用户的所有笔记")
    public ResponseEntity<List<Note>> searchNotes(@RequestParam String keyword) {
        List<Note> notes = noteService.searchNotes(keyword);
        return ResponseEntity.ok(notes);
    }

    @GetMapping("/{notebookId}/notes")
    @Operation(summary = "获取指定笔记本下的所有笔记")
    @SecurityRequirement(name = "BearerAuth")
    public ResponseEntity<List<Note>> getNotesInNotebook(@PathVariable Long notebookId) {
        List<Note> notes = noteService.getNotesByNotebook(notebookId);
        return ResponseEntity.ok(notes);
    }
}
